package io.github.yidasanqian.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    private Map<Long, User> userMap = new ConcurrentHashMap<>();

    @PostMapping("/user")
    public Object addUser(@RequestBody User user) {
        log.info("addUser user:{}", user);
        return userMap.put(user.getId(), user);
    }

    @PutMapping("/user")
    public Object updateUser(@RequestBody User user) {
        log.info("updateUser user:{}", user);
        return userMap.put(user.getId(), user);
    }

    @GetMapping("/user/{id}")
    public Object getUser(@PathVariable Long id) {
        log.info("getUser id:{}", id);
        return userMap.get(id);
    }

    @GetMapping("/user")
    public Object queryUsers(@RequestParam("ids") String ids) {
        log.info("queryUsers ids:{}", ids);
        List<User> userList = new ArrayList<>();
        String[] idArr = StringUtils.commaDelimitedListToStringArray(ids);
        Arrays.stream(idArr)
                .mapToLong(Long::valueOf)
                .forEach(id -> {
                    User user = userMap.get(id);
                    userList.add(user);
                });

        return userList;
    }
}
